package com.yash.rms.controller;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.io.IOUtils;
import org.springframework.roo.addon.web.mvc.controller.json.RooWebJson;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;

import com.yash.rms.domain.Bu;
import com.yash.rms.domain.Designations;
import com.yash.rms.domain.Grade;
import com.yash.rms.domain.Location;
import com.yash.rms.domain.Ownership;
import com.yash.rms.domain.Project;
import com.yash.rms.domain.Resource;
import com.yash.rms.domain.Visa;

@RequestMapping("/resources")
@Controller
@RooWebScaffold(path = "resources", formBackingObject = Resource.class)
@RooWebJson(jsonObject = Resource.class)
public class ResourceController {
	
	
	@InitBinder
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder)
			throws ServletException {
		binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
	}
	
	  @RequestMapping(method = RequestMethod.POST, produces = "text/html")
	    public String create(@Valid Resource resource,
	    		BindingResult bindingResult, Model uiModel, FileUpload  content, HttpServletRequest httpServletRequest) {
	        if (bindingResult.hasErrors()) {
	            populateEditForm(uiModel, resource);
	            return "redirect:/resources";
	        }
	        uiModel.asMap().clear();
	        if(resource.getCurrentProjectId().getId() < 0)resource.setCurrentProjectId(null);
	        try {
				resource.setResume(resource.getFile().getBytes());
				resource.setResumeFileName(resource.getFile().getOriginalFilename());
			} catch (IOException e1) {
			}
	        resource.persist();
	        return "redirect:/resources";
	    }
	  
	  @RequestMapping(method = RequestMethod.POST, produces = "text/html",params = "userAction=update")
	    public String update(@Valid Resource resource, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
		   if (bindingResult.hasErrors()) {
	            populateEditForm(uiModel, resource);
	            return "redirect:/resources";
	        }
	        uiModel.asMap().clear();
	        if(resource.getCurrentProjectId().getId() < 0)resource.setCurrentProjectId(null);
	        try {
				resource.setResume(resource.getFile().getBytes());
				resource.setResumeFileName(resource.getFile().getOriginalFilename());
			} catch (IOException e1) {
				Resource resource2=Resource.findResource(resource.getEmployeeId());
				resource.setResume(resource2.getResume());
				resource.setResumeFileName(resource2.getResumeFileName());
			}
	        resource.merge();
	        return "redirect:/resources";
	    }
	  
	  @RequestMapping(value = "/files/{id}", method = RequestMethod.GET )
	  public void getFile(@PathVariable("id") Integer employeeId, HttpServletResponse response) {
	      try {
	        // get your file as InputStream
	    	  Resource res = Resource.findResource(employeeId); 
	        byte[] is = res.getResume();
	        // copy it to response's OutputStream
	        ByteArrayInputStream bais = new ByteArrayInputStream(is);
	        IOUtils.copy(bais, response.getOutputStream());
	        response.setHeader("Content-Disposition","attachment; filename=\"" + res.getResumeFileName() +"\"");
	        response.flushBuffer();
	      } catch (IOException ex) {
	        throw new RuntimeException("IOError writing file to output stream");
	      }

	  }

	  
	  @RequestMapping(produces = "text/html")
	    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
	        if (page != null || size != null) {
	            int sizeNo = size == null ? 10 : size.intValue();
	            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
	            uiModel.addAttribute("resources", Resource.findResourceEntries(firstResult, sizeNo));
	            float nrOfPages = (float) Resource.countResources() / sizeNo;
	            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
	        } else {
	            uiModel.addAttribute("resources", Resource.findAllResources());
	        }
	        uiModel.addAttribute("designation", Designations.findAllDesignationses());
	        uiModel.addAttribute("ownership", Ownership.findAllOwnerships());
	        uiModel.addAttribute("location", Location.findAllLocations());
	        uiModel.addAttribute("visa", Visa.findAllVisas());
	        uiModel.addAttribute("grade", Grade.findAllGrades());
	        uiModel.addAttribute("bus", Bu.findAllBus());
	        uiModel.addAttribute("projects", Project.findAllProjects());
	        addDateTimeFormatPatterns(uiModel);
	        return "resources/list";
	    }
}
